package com.xz.freshmall.taomi;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.security.realidentity.RPVerify;
import com.huawei.android.hms.agent.HMSAgent;
import com.manor.common.BuildConfig;
import com.manor.common.CommonAppConfig;
import com.manor.common.CommonAppContext;
import com.manor.common.constant.LybConstant;
import com.manor.common.utils.KLog;
import com.manor.common.utils.L;
import com.manor.common.utils.SharedPreferencesUtils;
import com.manor.im.utils.PrivateConstants;
import com.manor.main.utils.Utils;
import com.uc.webview.export.cyclone.Constant;
import com.xz.freshmall.R;
import com.meizu.cloud.pushsdk.PushManager;
import com.meizu.cloud.pushsdk.util.MzSystemUtils;
import com.mob.MobSDK;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.imsdk.session.SessionWrapper;
import com.tencent.imsdk.utils.IMFunc;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMSDKConfig;
import com.tencent.qcloud.tim.uikit.TUIKit;
import com.tencent.qcloud.tim.uikit.base.IMEventListener;
import com.tencent.qcloud.tim.uikit.config.CustomFaceConfig;
import com.tencent.qcloud.tim.uikit.config.GeneralConfig;
import com.tencent.qcloud.tim.uikit.config.TUIKitConfigs;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationManagerKit;
import com.tencent.rtmp.TXLiveBase;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.trtc.TRTCCloud;
import com.tencent.ugc.TXUGCBase;

/**
 * Created by cxf on 2017/8/3.
 */
public class AppContext extends CommonAppContext {

    public static AppContext sInstance;


    @Override
    public void onCreate() {
        super.onCreate();
        sInstance = this;
        SharedPreferencesUtils.getInstance(this, LybConstant.SHAREDPREFERENCE_NAME);
        //闪验SDK配置debug开关 （必须放在初始化之前，开启后可打印闪验SDK更加详细日志信息）
//        OneKeyLoginManager.getInstance().setDebug(true);
        //闪验初始话
        initShanyanSDK(getApplicationContext());

        //腾讯云鉴权url
        String liveLicenceUrl = "http://license.vod2.myqcloud.com/license/v1/fb026d91473442cdfa568fa99b02d569/TXUgcSDK.licence";
        //腾讯云鉴权key
        String liveKey = "593b89606973d2602343fbb51189ad30";

        //初始化 ARouter
        if (BuildConfig.DEBUG) {
            ARouter.openLog();
            ARouter.openDebug();
            KLog.init(true);
        } else {
            KLog.init(false);
        }

        //初始化ShareSdk
        MobSDK.init(sInstance);
        //        MobSDK.init(sInstance, "319a33f944c8c", "822862983b435ec4695714eaac713a04");


        TUIKitConfigs configs = TUIKit.getConfigs();
        V2TIMSDKConfig v2TIMSDKConfig = new V2TIMSDKConfig();
        v2TIMSDKConfig.setLogLevel(V2TIMSDKConfig.V2TIM_LOG_DEBUG);
        configs.setSdkConfig(v2TIMSDKConfig);
        configs.setCustomFaceConfig(new CustomFaceConfig());
        configs.setGeneralConfig(new GeneralConfig());
        TUIKit.init(this, CommonAppConfig.TX_IM_APP_Id, configs);

        registerActivityLifecycleCallbacks(new StatisticActivityLifecycleCallback());

        ARouter.init(this);
        Logger.addLogAdapter(new AndroidLogAdapter());


        if (SessionWrapper.isMainProcess(getApplicationContext())) {
            PushInit();
        }
        new Handler().postDelayed(() -> {
            TXLiveBase.getInstance().setLicence(sInstance, liveLicenceUrl, liveKey);
            TXLiveBase.setConsoleEnabled(true);
            TRTCCloud.setConsoleEnabled(true);
            TXLiveBase.setLogLevel(TXLiveConstants.LOG_LEVEL_DEBUG);
            L.setDeBug(BuildConfig.DEBUG);
            //初始化腾讯bugly
             CrashReport.initCrashReport(sInstance, PrivateConstants.BUGLY_APPID, true);
             CrashReport.setAppVersion(sInstance, CommonAppConfig.getInstance().getVersion());


            //腾讯短视频
            String ugcKey = "593b89606973d2602343fbb51189ad30";
            String ugcLicenceUrl = "http://license.vod2.myqcloud.com/license/v1/fb026d91473442cdfa568fa99b02d569/TXUgcSDK.licence";
            TXUGCBase.getInstance().setLicence(sInstance, ugcLicenceUrl, ugcKey);
//            UGCKit.init(sInstance);

            initHeadRefreshLayout();
            Utils.iniwebview(this);
        }, 2000);

        RPVerify.init(getApplicationContext());

    }

    private void PushInit() {

        if (IMFunc.isBrandHuawei()) {
            // 华为离线推送
            HMSAgent.init(this);
        }
        if (MzSystemUtils.isBrandMeizu(this)) {
            // 魅族离线推送
            PushManager.register(this, PrivateConstants.MZ_PUSH_APPID, PrivateConstants.MZ_PUSH_APPKEY);
        }
        if (IMFunc.isBrandVivo()) {
            // vivo离线推送
            //  PushUtils.initpush(this);   在mainactivity启动
        }

    }


    /**
     * 设置上下拉刷新经典样式
     */
    private void initHeadRefreshLayout() {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator((context, layout) -> {
            layout.setPrimaryColorsId(R.color.transparent, R.color.gray_66);//全局设置主题颜色  第一个是背景 第二个是字体
            return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator((context, layout) -> {
            //指定为经典Footer，默认是 BallPulseFooter
            return new ClassicsFooter(context).setDrawableSize(20);
        });
    }


    /**
     * 初始化闪验
     *
     * @param context
     */
    private void initShanyanSDK(Context context) {
//        OneKeyLoginManager.getInstance().init(context, "LL79t2jq", new InitListener() {
//            @Override
//            public void getInitStatus(int code, String result) {
//                //闪验SDK初始化结果回调
//                Log.e("shanyanVVV", "初始化： code==" + code + "   result==" + result);
//            }
//        });
    }


    class StatisticActivityLifecycleCallback implements ActivityLifecycleCallbacks {
        private int foregroundActivities = 0;
        private boolean isChangingConfiguration;
        private final IMEventListener mIMEventListener = new IMEventListener() {
            @Override
            public void onNewMessage(V2TIMMessage msg) {
                // MessageNotification notification = MessageNotification.getInstance();
                // notification.notify(msg);
            }
        };

        private final ConversationManagerKit.MessageUnreadWatcher mUnreadWatcher = new ConversationManagerKit.MessageUnreadWatcher() {
            @Override
            public void updateUnread(int count) {
                // 华为离线推送角标
                //HUAWEIPushReceiver.updateBadge(this, count);
            }
        };

        @Override
        public void onActivityCreated(Activity activity, Bundle bundle) {
            KLog.i("AppContext", "onActivityCreated bundle: " + bundle);
        }

        @Override
        public void onActivityStarted(Activity activity) {
            foregroundActivities++;
            if (foregroundActivities == 1 && !isChangingConfiguration) {
                // 应用切到前台
                KLog.i("AppContext", "application enter foreground");
                V2TIMManager.getOfflinePushManager().doForeground(new V2TIMCallback() {
                    @Override
                    public void onError(int code, String desc) {
                        KLog.e("AppContext", "doForeground err = " + code + ", desc = " + desc);
                    }

                    @Override
                    public void onSuccess() {
                        KLog.i("AppContext", "doForeground success");
                    }
                });
                TUIKit.removeIMEventListener(mIMEventListener);
                ConversationManagerKit.getInstance().removeUnreadWatcher(mUnreadWatcher);
                //MessageNotification.getInstance().cancelTimeout();
            }
            isChangingConfiguration = false;
        }

        @Override
        public void onActivityResumed(Activity activity) {
        }

        @Override
        public void onActivityPaused(Activity activity) {
        }

        @Override
        public void onActivityStopped(Activity activity) {
            foregroundActivities--;
            if (foregroundActivities == 0) {
                // 应用切到后台
                KLog.i("AppContext", "application enter background");
                int unReadCount = ConversationManagerKit.getInstance().getUnreadTotal();
                V2TIMManager.getOfflinePushManager().doBackground(unReadCount, new V2TIMCallback() {
                    @Override
                    public void onError(int code, String desc) {
                        KLog.e("AppContext", "doBackground err = " + code + ", desc = " + desc);
                    }

                    @Override
                    public void onSuccess() {
                        KLog.i("AppContext", "doBackground success");
                    }
                });
                // 应用退到后台，消息转化为系统通知
                TUIKit.addIMEventListener(mIMEventListener);
                ConversationManagerKit.getInstance().addUnreadWatcher(mUnreadWatcher);
            }
            isChangingConfiguration = activity.isChangingConfigurations();
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {

        }
    }


}
